const nodemailer = require('nodemailer');
const config = require('./config');

// 创建邮件发送器
const transporter = nodemailer.createTransport({
  host: config.email.host,
  port: config.email.port,
  secure: config.email.secure,
  auth: {
    user: config.email.user,
    pass: config.email.pass
  }
});

// 验证邮件发送器配置
const verifyTransporter = async () => {
  try {
    await transporter.verify();
    return true;
  } catch (error) {
    console.error('邮件发送器配置失败:', error);
    return false;
  }
};

// 发送验证码邮件
const sendVerificationEmail = async (email, code) => {
  try {
    // 邮件模板
    const mailOptions = {
      from: `"棋牌室" <${config.email.user}>`,
      to: email,
      subject: '棋牌室登录验证码',
      html: `
        <div style="background-color:#f5f5f5;padding:20px;">
          <div style="background-color:#fff;border-radius:10px;padding:20px;max-width:600px;margin:0 auto;">
            <h2 style="color:#333;text-align:center;">棋牌室登录验证</h2>
            <p style="color:#666;">尊敬的用户：</p>
            <p style="color:#666;">您正在登录棋牌室应用，验证码为：</p>
            <div style="background-color:#f8f8f8;padding:15px;text-align:center;font-size:24px;font-weight:bold;color:#333;margin:15px 0;letter-spacing:5px;">
              ${code}
            </div>
            <p style="color:#666;">验证码有效期为${config.verification.expireMinutes}分钟，请勿将验证码泄露给他人。</p>
            <p style="color:#666;">如非本人操作，请忽略此邮件。</p>
            <p style="color:#999;font-size:12px;text-align:center;margin-top:30px;">本邮件由系统自动发送，请勿回复</p>
          </div>
        </div>
      `
    };

    // 发送邮件
    const info = await transporter.sendMail(mailOptions);
    return true;
  } catch (error) {
    console.error('验证码邮件发送失败:', error);
    return false;
  }
};

module.exports = {
  transporter,
  verifyTransporter,
  sendVerificationEmail
}; 